import Vue from 'vue'
import co from 'co'
import * as Util from '../components/Util'

let changeMeterGen = function * (model, row) {
  if (row.f_meter_classify === '机表' || row.f_meter_classify === '物联网表' || row.f_meter_classify === '远传表') {
    let handplan = {
      f_last_tablebase: row.f_meter_base,
      f_tablebase: model.f_tablebase - 0,
      f_whether_pay: '否',
      f_oughtamount: (model.f_tablebase - 0) - (row.f_meter_base - 0),
      f_meter_state: '已抄表',
      f_operator: Util.f.name,
      f_inputtor: Util.f.name,
      f_hand_date: Util.toStandardTimeString(),
      f_input_date: Util.toStandardTimeString(),
      f_end_date: Util.addDate(Util.toStandardTimeString(), model.lazy),
      f_price_id: row.f_price_id,
      userfile: row.f_user_id,
      record_userinfo: row.f_userinfo_id,
      f_userinfo_id: row.f_userinfo_id,
      f_user_name: row.f_user_name,
      f_user_type: row.f_user_type,
      f_waterproperties: row.f_waterproperties,
      f_address: row.f_address,
      f_meter_brand: row.f_meter_brand,
      f_meter_style: row.f_meter_style,
      f_meternumber: row.f_meternumber,
      f_filiale: Util.f.f_fengongsi,
      f_outlets: Util.f.f_parentname
    }
    return Vue.resetpost('rs/logic/machineOwe', {data: {row: row, handplan: handplan}}, {resolveMsg: null, rejectMsg: null})
  } else if (row.f_meter_classify === '水量卡表') {
    let overuse = {
      f_overuseamount: (model.f_tablebase - 0) - (row.f_meter_base - 0),
      f_overusefee: '',
      f_whether_pay: '否',
      f_overuse_state: '有效',
      f_user_id: row.f_user_id,
      record_userinfo: row.f_userinfo_id,
      f_userinfo_id: row.f_userinfo_id,
      f_user_name: row.f_user_name,
      f_address: row.f_address,
      f_operat_type: '卡表超用',
      f_describe: `${Util.f.name}对用户${row.f_user_name}的${row.f_meter_brand}表进行超用收费操作`,
      f_state: '有效',
      f_operator: Util.f.name,
      f_filiale: Util.f.f_fengongsi,
      f_outlets: Util.f.f_parentname
    }

    return Vue.resetpost('rs/logic/cardMeterOwe', {data: {row: row, overuse: overuse}}, {resolveMsg: null, rejectMsg: '超用收费存库失败'})

  } else if (row.f_meter_classify === '金额卡表') {
    let overuse = {
      f_overusefee: (0 - (model.f_tablebase - 0)),
      f_whether_pay: '否',
      f_overuse_state: '有效',
      f_user_id: row.f_user_id,
      record_userinfo: row.f_userinfo_id,
      f_userinfo_id: row.f_userinfo_id,
      f_user_name: row.f_user_name,
      f_address: row.f_address,
      f_operat_type: '卡表超用',
      f_describe: `${Util.f.name}对用户${row.f_user_name}的${row.f_meter_brand}表进行超用收费操作`,
      f_state: '有效',
      f_operator: Util.f.name,
      f_filiale: Util.f.f_fengongsi,
      f_outlets: Util.f.f_parentname
    }
    return Vue.resetpost('rs/logic/feeMeterOwe', {data: {row: row, overuse: overuse}}, {resolveMsg: null, rejectMsg: '超用收费存库失败'})
  }
}

// 只换表
let onlyChangeNewMeterGen = function * (model, data) {
  let result
  try {
    // 存库
    result = yield Vue.resetpost('rs/logic/changeMeter', {data: data}, {resolveMsg: null, rejectMsg: '换表失败'})
    // 获取水价和售水情况参数
    let cardParams = yield co(getParamGen(result.data.cardnumber))
    // 写卡
    let params = {
      factory: model.metermessage.waterbrand[0].f_alias,
      kzt: '0',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
      kh: result.data.cardnumber,                          // 卡号
      yhh: data.f_meterid,                                            // 用户号，档案中自己输
      ql: 0,                                               // 预购水量
      csql: 0,                                           // 上次购水量，新开户为0
      ccsql: 0,                                          // 上上次购水量，新开户为0
      cs: 1,                                             // 求购水次数，先开户为1
      ljgql: 0,                                            // 当前累计购水量
      bkcs: 0,                                           // 新开户卡，为0
      ljyql: 0,                                          // 累积用水量，有些表要累加原来用水量,新开户卡，为0
      bjql: model.metermessage.waterbrand[0].f_police_water,                              // 报警水量,t_waterbrand表中
      czsx: model.metermessage.waterbrand[0].f_topup_ceil,                              // 充值上线，t_waterbrand表中
      tzed: model.metermessage.waterbrand[0].f_overdr_lines,                            // 透支额度，t_waterbrand表中
      cssqrq: '',                                          // 上次售水日期，格式为YYYYMMDD
      meterid: model.metermessage.f_meternumber,                          // 表号
      totalmoney: cardParams.data.f_collection             // 累计金额
    }
    let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '补水卡服务错误'}))
    // 卡服务写卡异常，业务逻辑回滚

    if (!result || !cardParams || !cardRes || cardRes.data.Err || cardRes.data.Exception) {
      let data = {
        id: result.data.id
      }
      yield Vue.resetpost('rs/logic/changeMeterRollback', {data: data}, {resolveMsg: '换表成功，写卡失败', rejectMsg: '换表成功，写卡失败'})
    } else {
      let change = {
        userfiles: {
          f_user_id: data.f_user_id,
          version: data.version,
          f_card_id: result.data.cardnumber,
          f_times: 0,
          f_card_password: cardRes.data.Kmm
        },
        record: {
          id: result.data.id,
          f_state: '有效'
        }
      }
      yield Vue.resetpost('rs/logic/updatemark', {data: change}, {resolveMsg: '换表成功', rejectMsg: '换表成功，更新状态有效失败'})
    }
  } catch (error) {
    let data = {
      id: result.data.id
    }
    yield Vue.resetpost('rs/logic/changeMeterRollback', {data: data}, {resolveMsg: '换表成功，写卡失败', rejectMsg: '换表成功，写卡失败'})
  }
}

let changeNewMeterGen = function * (type, data) {
  if (type === '物联网表') {
    data.changemeter.userfiles.f_table_state = '未发送'
  }
  return co(Vue.resetpost('rs/logic/changeMeter', {data: data}))
}

// 换表并补水

let changeAndPlusGen = function * (self, model, row) {
  let result
  try {
    let data = self.getData(model, row)
    data.changemeter.userfiles.f_times = 1
    data.changemeter.userfiles.f_remanent_water = (model.f_newremanent_water - 0) - (model.f_prewater - 0)
    data.changemeter.userfiles.f_meter_base = (model.metermessage.f_meter_base - 0) + (model.f_prewater - 0)
    data.changemeter.f_state = '未知'
    // 返回卡号
    result = yield Vue.resetpost('rs/logic/changeMeter', {data: data}, {resolveMsg: null, rejectMsg: '换表并补水卡服务错误'})
    // 获取水价和售水情况参数
    let cardParams = yield co(getParamGen(result.data.cardnumber))
    // 写卡
    let params = {
      factory: model.metermessage.waterbrand[0].f_alias,
      kzt: '0',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
      kh: result.data.cardnumber,                          // 卡号
      yhh: data.f_meterid,                                 // 用户号，档案中自己输
      ql: model.f_prewater,                                  // 预购水量
      csql: cardParams.data.sc,                            // 上次购水量，新开户为0
      ccsql: cardParams.data.ssc,                          // 上上次购水量，新开户为0
      cs: '1',                                             // 求购水次数，先开户为1
      ljgql: model.f_prewater,                               // 当前累计购水量
      bkcs: '0',                                           // 新开户卡，为0
      ljyql: '0',                                          // 累积用水量，有些表要累加原来用水量,新开户卡，为0
      bjql: model.metermessage.waterbrand[0].f_police_water,   // 报警水量,t_waterbrand表中
      czsx: model.metermessage.waterbrand[0].f_topup_ceil,   // 充值上线，t_waterbrand表中
      tzed: model.metermessage.waterbrand[0].f_overdr_lines, // 透支额度，t_waterbrand表中
      cssqrq: '',                                          // 上次售水日期，格式为YYYYMMDD
      meterid: row.f_meternumber,                          // 表号
      totalmoney: cardParams.data.f_collection             // 累计金额
    }
    let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '换表并补水卡服务错误'}))
    if (!result || !cardParams || !cardRes || cardRes.data.Err || cardRes.data.Exception) {
      // 换表业务进行手动回滚
      yield Vue.resetpost('rs/logic/changeMeterRollback', {data: {id: result.data.id, fillwater_id: result.data.fillwater_id}}, {resolveMsg: '换表并补水失败', rejectMsg: '换表并补水失败'})
    } else {
      // 如果成功修改标识(更新状态为有效)，将返回的卡密码写回数据库
      let pluswater = {
        userfiles: {
          f_user_id: data.f_user_id,
          f_times: 1,
          version: data.version,
          f_card_id: result.data.cardnumber,
          f_card_password: cardRes.data.Kmm
        },
        record: {
          id: result.data.fillwater_id,
          f_state: '有效'
        }
      }
      let changemeter = {
        userfiles: {},
        record: {
          id: result.data.id,
          f_state: '有效'
        }
      }
      yield Vue.resetpost('rs/logic/updatemark', {data: changemeter}, {resolveMsg: null, rejectMsg: null})
      yield Vue.resetpost('rs/logic/updatemark', {data: pluswater}, {resolveMsg: '换表并补水成功', rejectMsg: '换表并补水修改状态失败'})
    }
  } catch (error) {
    yield Vue.resetpost('rs/logic/changeMeterRollback', {data: {id: result.data.id, fillwater_id: result.data.fillwater_id}}, {resolveMsg: '换表并补水失败', rejectMsg: '换表并补水失败'})
  }
}

// 单独换表补水界面

let AddWaterWriteCardGen = function * (model, row) {
  let result
  try {
    // 存库
    result = yield co(AddWaterGen(model, row))
    // 获取水价和售水情况参数
    let cardParams = yield co(getParamGen(row.f_card_id))
    // 写卡
    let params = {
      factory: row.f_alias,                                // 水表厂家
      kh: row.f_card_id,                                   // 卡号
      yhh: cardParams.data.f_meterid,                      // 用户号，档案中自己输
      bjql: row.f_police_water,                              // 报警水量,t_waterbrand表中
      czsx: row.f_topup_ceil,                              // 充值上线，t_waterbrand表中
      tzed: row.f_overdr_lines,                            // 透支额度，t_waterbrand表中
      bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
      ql: model.f_fillwater,                                  // 预购水量
      csql: cardParams.data.sc,                            // 上次购水量，新开户为0
      ccsql: cardParams.data.ssc,                          // 上上次购水量，新开户为0
      cs: 1,                                               // 求购水次数，先开户为1
      ljgql: cardParams.data.f_prewater,                     // 当前累计购水量
      ljyql: cardParams.data.f_prewaterall,                  // 累积用水量，有些表要累加原来用水量,新开户卡，为0
      totalmoney: cardParams.data.f_collection             // 累计金额
    }
    let cardRes
    if (row.f_states === '换表') {
      cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '补水卡服务错误'}))
    } else {
      params.cs = row.cardInfo.Times + 1
      cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteGasCard', params, {resolveMsg: null, rejectMsg: '补水卡服务错误'}))
    }
    // 卡服务写卡异常，业务逻辑回滚

    if (!result || !cardParams || !cardRes || cardRes.data.Err || cardRes.data.Exception) {
      let data = {
        userfile: {
          f_user_id: row.f_user_id,
          f_remanent_water: model.f_lastremain_fillwater,
          version: 0
        },
        fillwater_id: result.data + ''
      }
      yield Vue.resetpost('rs/logic/addWaterRoolBack', {data: {userfile: data.userfile, fillwater_id: data.fillwater_id}}, {resolveMsg: '补水失败', rejectMsg: '补水失败'})
    } else {
      let update = {
        userfiles: {
          f_user_id: row.f_user_id,
          f_meter_base: (row.f_meter_base - 0) + (model.f_fillwater - 0),
          f_remanent_water: model.f_theremain_fillwater,
          f_times: 1,
          version: 0
        },
        record: {
          id: result.data,
          f_state: '有效'
        }
      }
      yield Vue.resetpost('rs/logic/updatemark', {data: update}, {resolveMsg: '补水成功', rejectMsg: '补水修改状态失败'})
    }
  } catch (error) {
    let data = {
        userfile: {
          f_user_id: row.f_user_id,
          f_remanent_water: model.f_lastremain_fillwater,
          version: 0
        },
        fillwater_id: result.data + ''
      }
  Vue.resetpost('rs/logic/addWaterRoolBack', {data: {userfile: data.userfile, fillwater_id: data.fillwater_id}}, {resolveMsg: '补水失败', rejectMsg: '补水失败'})
  }
}

let AddWaterGen = function * (model, row) {
  let data = {
    fillwater: {
      f_meter_brand: row.f_meter_brand,
      f_fillwater: model.f_fillwater,
      f_card_id: row.f_card_id,
      f_lastremain_fillwater: model.f_lastremain_fillwater,
      f_theremain_fillwater: model.f_theremain_fillwater,
      f_reason: model.f_reason,
      f_fillwater_type: model.f_fillwater_type[0],
      f_fillwater_state: '有效',
      f_userinfo_id: row.f_userinfo_id,
      f_user_id: row.f_user_id,
      record_userinfo: row.f_userinfo_id,
      f_user_name: row.f_user_name,
      f_operat_type: '补水',
      f_describe: `${Util.f.name}对用户${row.f_user_name}进行补水操作`,
      f_state: '未知',
      f_operator: Util.f.name,
      userfile: {
        f_user_id: row.f_user_id,
        f_remanent_water: model.f_theremain_fillwater,
        version: row.version
      }
    }
  }
  data.fillwater.userfile.f_times = row.states === '换表' ? 1 : row.cardInfo.Times + 1
  return co(Vue.resetpost('rs/logic/changePlus', {data: data}, {resolveMsg: null, rejectMsg: '换表水补水存库失败'}))
}
let getParamGen = function * (id) {
  let data = {
    f_card_id: id
  }
  return co(Vue.resetpost('rs/logic/stairCard', {data: data}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'}))
}
let ChangeMeterService = {
  install (Vue, options) {
    // 给vue增添对话框显示方法

    Vue.ChangeMeterService = Vue.prototype.$ChangeMeterService = ChangeMeterService
  },
  // 换表

  changeMeter (model, row) {
    let change = changeMeterGen(model, row)
    return co(change)
  },
  getData (model, row) {
    return {
      changemeter: {
        userfiles: {
          f_user_id: row.f_user_id,
          f_position: model.metermessage.f_position[0],
          f_meter_base: model.metermessage.f_meter_base === '' ? 0 : model.metermessage.f_meter_base,
          f_meternumber: model.metermessage.f_meternumber,
          f_metertitles: model.metermessage.f_metertitles,
          f_meter_classify: model.metermessage.waterbrand[0].f_meter_type,
          f_waterbrand_id: model.metermessage.waterbrand[0].id,
          f_watermodel_id: model.metermessage.watermodel[0].id,
          f_remanent_water: model.f_newremanent_water,
          f_price_id: row.f_price_id,
          f_card_id: '',
          f_times: 0,
          f_initial_base: model.metermessage.f_meter_base === '' ? 0 : model.metermessage.f_meter_base,
          f_table_state: '正常',
          f_user_type: row.f_user_type,
          f_waterproperties: row.f_waterproperties,
          version: row.version
        },
        f_user_id: row.f_user_id,
        f_userinfo_id: row.f_userinfo_id,
        f_user_name: row.f_user_name,
        f_changemeter_type: model.f_changemeter_type[0],
        f_changemeter_fee: model.f_changemeter_fee,
        f_meternumber: row.f_meternumber,
        f_newmeternumber: model.metermessage.f_meternumber,
        f_metertitles: row.f_metertitles,
        f_newmetertitles: model.metermessage.f_metertitles,
        f_card_id: row.f_card_id,
        f_newcard_id: '',
        f_card_password: row.f_card_password,
        f_newcard_password: '',
        f_meter_base: row.f_meter_base,
        f_newmeter_base: model.metermessage.f_meter_base === '' ? 0 : model.metermessage.f_meter_base,
        f_initial_base: row.f_initial_base,
        f_newinitial_base: model.metermessage.f_meter_base === '' ? 0 : model.metermessage.f_meter_base,
        f_times: row.times,
        f_newtimes: 0,
        f_meter_classify: row.f_meter_classify,
        f_newmeter_classify: model.metermessage.waterbrand[0].f_meter_type,
        f_meterid: row.f_meterid,
        f_newmeterid: '',
        f_remanent_water: row.f_remanent_water,
        f_newremanent_water: model.f_newremanent_water,
        // 物联网表
        f_table_state: row.f_table_state,
        f_newtable_state: '待发送',
        f_valve_state: row.f_valve_state,
        f_newvalve_state: '待发送',
        f_waterbrand_id: row.f_waterbrand_id,
        f_newwaterbrand_id: model.metermessage.waterbrand[0].id,
        f_watermodel_id: row.f_watermodel_id,
        f_newwatermodel_id: model.metermessage.watermodel[0].id,
        f_changemeter_state: '有效',
        record_userinfo: row.f_userinfo_id,
        f_reason: model.f_reason[0],
        f_othereason: model.f_othereason,
        f_operat_type: '换表',
        f_describe: `${Util.f.name}对用户${row.f_user_name}进行换新表操作`,
        f_state: '有效',
        f_operator: Util.f.name,
        f_filiale: Util.f.f_fengongsi,
        f_outlets: Util.f.f_parentname,
        f_change_operator: model.f_change_operator,
        f_changemeter_date: model.f_changemeter_date
      },
      // 是否换成卡表
      changeToCard: model.isCardMeter,
      // 是否补水
      isfillwater: model.isfillwater,
      // 水表品牌，用于获取卡号
      waterbrand: model.metermessage.waterbrand[0].f_meter_brand,
      // 更新账户结余
      f_oldbalance: row.f_balance,
      userinfo_version: row.userinfo_version,
      f_newbalance: model.f_newbalance,
      fillwater: {
        f_card_id: row.f_card_id,
        f_fillwater: model.f_prewater,
        f_lastremain_fillwater: model.f_newremanent_water,
        f_theremain_fillwater: (model.f_newremanent_water - 0) - (model.f_prewater - 0),
        f_reason: '换新表时旧表有剩余',
        f_fillwater_type: '换表补水',
        f_fillwater_state: '有效',
        f_user_id: row.f_user_id,
        record_userinfo: row.f_userinfo_id,
        f_userinfo_id: row.f_userinfo_id,
        f_user_name: row.f_user_name,
        f_operat_type: '补水',
        f_describe: `${Util.f.name}对用户${row.f_user_name}进行补水操作`,
        f_state: '未知',
        f_operator: Util.f.name,
        f_filiale: Util.f.f_fengongsi,
        f_outlets: Util.f.f_parentname,
        userfile: {
          f_times: 1,
          f_user_id: row.f_user_id,
          version: row.version,
          f_remanent_water: (model.f_newremanent_water - 0) - (model.f_prewater - 0)
        }
      }
    }
  },
  changeAndPlus (model, row) {
    return co(changeAndPlusGen(this, model, row))
  },
  changeNewMeter (model, row) {
    // 换成机表不做写卡操作

    if (model.metermessage.waterbrand[0].f_meter_type === '物联网表' ||
        model.metermessage.waterbrand[0].f_meter_type === '远传表' ||
        model.metermessage.waterbrand[0].f_meter_type === '机表') {
      return co(changeNewMeterGen(model.metermessage.waterbrand[0].f_meter_type, this.getData(model, row)))
    } else {
      return co(onlyChangeNewMeterGen(model, this.getData(model, row)))
    }
  },
  overCharge (model, row) {
    let data = {
      record_userinfo: row.f_userinfo_id,
      f_balance: model.f_balance,
      f_curbalance: model.f_curbalance,
      f_meter_type: row.f_meter_classify,
      f_preamount: model.f_preamount,
      f_prewater: model.f_prewater,
      f_payment: model.f_payment[0],
      f_price_id: row.f_price_id,
      f_user_id: row.f_user_id,
      f_user_name: row.f_user_name,
      f_user_type: row.f_user_type,
      f_waterproperties: row.f_waterproperties,
      f_address: row.f_address,
      f_meter_brand: row.f_meter_brand,
      f_meter_style: row.f_meter_style,
      f_meternumber: row.f_meternumber,
      f_collection: model.f_collection,
      f_delaypay: 0,
      f_operator: Util.f.name,
      f_filiale: Util.f.f_fengongsi,
      f_outlets: Util.f.f_parentname,
      f_charge_type: '超用收费',
      f_charge_state: '有效',
      f_operat_type: '超用收费',
      f_describe: `换表超用,${Util.f.name}对用户${row.f_user_name}进行卡表超用操作`,
      f_state: '有效',
      over: {
        id: model.over_id,
        f_whether_pay: '是'
      }
    }
    if (row.f_meter_classify === '金额卡表') {
      data.f_tablebase = 0
      data.f_last_tablebase = row.f_meter_base
      data.userinfo = {
        f_userinfo_id: row.f_userinfo_id,
        version: row.userinfo_version,
        f_balance: (row.f_balance - 0) - (model.f_preamount - 0) + (model.f_collection - 0),
        userfiles: {
          f_user_id: model.f_user_id,
          f_meter_base: parseFloat(model.f_prewater) + parseFloat(row.f_meter_base),
          version: row.version
        }
      }
    } else if (row.f_meter_classify === '水量卡表') {
      data.f_tablebase = model.f_prewater
      data.f_last_tablebase = row.f_meter_base
      data.userinfo = {
        f_userinfo_id: row.f_userinfo_id,
        version: row.userinfo_version,
        f_balance: (row.f_balance - 0) - (model.f_preamount - 0) + (model.f_collection - 0),
        userfiles: {
          f_user_id: model.f_user_id,
          f_meter_base: parseFloat(model.f_prewater) + parseFloat(row.f_meter_base),
          version: row.version
        }
      }
    }
    return Vue.resetpost('rs/logic/overCharge', {data: data}, {resolveMsg: '超用收费成功', rejectMsg: '超用收费失败'})
  },
  AddWaterWriteCard (model, row) {
    return co(AddWaterWriteCardGen(model, row))
  }
}

export default ChangeMeterService
